package com.example.firstapp.broadcast

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.firstapp.R
// 动态注册广播接收器receiver  不是注册广播
class broadcast1 : AppCompatActivity() {
    lateinit var timeChangeReceiver: TimeChangeReceiver
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_broadcast1)
        // 1、创建了一个IntentFilter的实例
        val intentFilter = IntentFilter()
        // 2、添加一个广播的动作  即接收的广播名
        intentFilter.addAction("android.intent.action.TIME_TICK")
        // 3、创建接收广播的实例(TimeChangeReceiver) 自定义的，接收广播的响应
        timeChangeReceiver = TimeChangeReceiver()
        // 4、注册
        // IntentFilter的实例（有广播动作）和TimeChangeReceiver的实例
        registerReceiver(timeChangeReceiver, intentFilter)
    }
    override fun onDestroy() {
        super.onDestroy()
        // Activity销毁时取消注册
        unregisterReceiver(timeChangeReceiver)
    }
    // 定义了一个内部类TimeChangeReceiver,继承BroadcastReceiver
    // 重写父类BroadcastReceiver的onReceive()方法，这个方法是收到广播后执行的
    inner class TimeChangeReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            Toast.makeText(context, "Time has changed11", Toast.LENGTH_SHORT).show()
        }
    }
}